import type * as Koa from 'koa';
import { v4 as uuidV4 } from 'uuid';

export const traceHeaderKey = 'cns-proxy-request-id';

export default async (context: Koa.Context, next: Koa.Next) => {
  const requestId = uuidV4();
  if (!context.request.headers[traceHeaderKey]) {
    // 统一向下游服务传递 request id，比如 EOP API 和 CAS 服务
    context.request.headers[traceHeaderKey] = requestId;
  }
  if (!context.response.headers[traceHeaderKey]) {
    // 统一在 reponse header 里向浏览器返回 request id
    context.set(traceHeaderKey, requestId);
  }
  await next();
};
